@echo off
setlocal

:: 设置变量
set APP_NAME=open_ipc_client
set SOURCE_DIR=%~dp0
set DEPLOY_DIR=%SOURCE_DIR%deploy
set BIN_DIR=%SOURCE_DIR%bin

echo 开始打包 %APP_NAME%...

:: 清理并创建部署目录
if exist "%DEPLOY_DIR%" (
    echo 清理旧的部署目录...
    rmdir /s /q "%DEPLOY_DIR%"
)
mkdir "%DEPLOY_DIR%"

:: 复制可执行文件
echo 复制可执行文件...
copy "%BIN_DIR%\%APP_NAME%.exe" "%DEPLOY_DIR%\"

:: 复制FFmpeg DLL文件
echo 复制FFmpeg依赖库...
copy "%BIN_DIR%\*.dll" "%DEPLOY_DIR%\"

::查找Qt安装路径中的windeployqt工具
echo 查找Qt工具...
set WINDEPLOYQT_PATH=D:\Qt\Qt5.14.0\5.14.0\msvc2017_64\bin\windeployqt.exe

:: 检查指定路径是否存在
if exist "%WINDEPLOYQT_PATH%" (
    goto :found_windeployqt
)

:: 如果指定路径不存在，尝试自动查找
set WINDEPLOYQT_PATH=
for /f "tokens=*" %%i in ('where qmake 2^>nul') do (
    for %%j in ("%%~dpi..") do (
        if exist "%%~j\bin\windeployqt.exe" (
            set WINDEPLOYQT_PATH=%%~j\bin\windeployqt.exe
            goto :found_windeployqt
        )
    )
)

:: 如果没找到，尝试常见的Qt安装路径
if not defined WINDEPLOYQT_PATH (
    for %%p in (
        "C:\Qt\*\*\bin\windeployqt.exe"
        "D:\Qt\*\*\bin\windeployqt.exe"
        "C:\Qt\Tools\*\bin\windeployqt.exe"
        "%QTDIR%\bin\windeployqt.exe"
    ) do (
        for /f %%i in ('dir /b /s "%%p" 2^>nul') do (
            set WINDEPLOYQT_PATH=%%i
            goto :found_windeployqt
        )
    )
)

:found_windeployqt
if not defined WINDEPLOYQT_PATH (
    echo 错误: 未找到windeployqt工具！
    echo 请确保Qt已正确安装，或者手动设置QTDIR环境变量
    pause
    exit /b 1
)

echo 找到windeployqt: %WINDEPLOYQT_PATH%

:: 使用windeployqt工具部署Qt依赖
echo 部署Qt依赖库...
"%WINDEPLOYQT_PATH%" --release --no-translations --no-system-d3d-compiler --no-opengl-sw "%DEPLOY_DIR%\%APP_NAME%.exe"

:: 检查部署结果
if errorlevel 1 (
    echo 部署过程中出现错误！
    pause
    exit /b 1
)

echo.
echo 打包完成！
echo 部署目录: %DEPLOY_DIR%
echo.
echo 你可以将整个deploy文件夹复制到其他Windows机器上运行
echo 可执行文件: %DEPLOY_DIR%\%APP_NAME%.exe
echo.
pause
